package ths

import (
	"fmt"
	s "gitee.com/gcom/stockdock/core/support"
	"gitee.com/gcom/stockdock/spider/ths"
	"time"
)

// 更新同花顺行业列表
func UpdateIndustryList(ctx s.TracerCtx) error {
	li, err := ths.IndustryQuoteListThs(ctx)
	if err != nil {
		s.WriteErrEvent(ctx, "查询行业列表失败", err)
		return err
	}
	s.WriteEvent(ctx, fmt.Sprintf("查询爬取到同花顺行业%d条", len(li)))

	entities := make([]*ths.IndustryThsEntity, 0, len(li))
	for _, v := range li {
		entities = append(entities, &ths.IndustryThsEntity{IndustryQuoteThs: v})
	}
	_, err = ths.UpdateIndustryList(ctx.DB, entities)
	if err != nil {
		s.WriteErrEvent(ctx, "更新行业列表失败", err)
		return err
	}
	s.WriteEvent(ctx, fmt.Sprintf("成功更新%d条", len(li)))
	return nil
}

// 更新行业股票列表
func UpdateIndustryStocks(ctx s.TracerCtx) error {
	li, err := ths.IndustryQuoteListThs(ctx)
	if err != nil {
		s.WriteErrEvent(ctx, "查询行业列表失败", err)
		return err
	}
	s.WriteEvent(ctx, fmt.Sprintf("共有行业%d个", len(li)))

	var total = 0
	var entities = make([]*ths.StockThsEntity, 0, 200)
	var ch = make(chan ths.QuotePageEventThs)
	defer close(ch)
	for i, ind := range li {
		go func() {
			err = ths.IndustryStockListThs(ctx, ind.Code, ch)
			ctx.Logger.Infof("行业[%s,%s]的股票列表刷新完成", ind.Code, ind.Name)
		}()
		s.WriteEvent(ctx, fmt.Sprintf("[%d/%d]获取行业[%s-%s]股票列表", i+1, len(li), ind.Code, ind.Name))

		var pageNo, pageCount, count = 1, 1, 0
		for page := range ch {
			if page.Err != nil {
				s.WriteErrEvent(ctx, "获取股票列表异常", page.Err)
				return page.Err
			}

			if pageCount < page.PageCount {
				pageCount = page.PageCount
			}
			s.WriteEvent(ctx, fmt.Sprintf("第%d/%d页，获取股票%d条", pageNo, pageCount, len(page.Data)))

			for _, q := range page.Data {
				entities = append(entities, &ths.StockThsEntity{DailyQuoteThs: q, Incode: ind.Code})
			}
			if len(entities) >= 200 || (pageNo == pageCount && len(entities) > 0) {
				_, e := ths.UpdateStockThs(ctx.DB, entities)
				if e != nil {
					s.WriteErrEvent(ctx, "更新行业股票列表失败", e)
					return e
				}
				total += len(entities)
				count += len(entities)
				entities = entities[:0]
			}

			if pageNo == pageCount {
				s.WriteEvent(ctx, fmt.Sprintf("行业[%s,%s]下股票%d支写入数据库", ind.Code, ind.Name, count))
				break
			}

			time.Sleep(1 * time.Second)
			pageNo += 1
		}
	}

	if err != nil {
		s.WriteErrEvent(ctx, "更新行业股票列表失败", err)
		return err
	}
	s.WriteEvent(ctx, fmt.Sprintf("完成行业股票列表更新，共%d条", total))
	return nil
}
